package com.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author :admin
 * @description: 线程变量共享，解决
 * 多线程下未同步存在线程安全（Lock方式实现同步）
 * @create date: 2019/4/3 10:53
 */
public class ThreadShare_solve1 implements Runnable{

    private String shareName;

    public ThreadShare_solve1(String shareName) {
        this.shareName = shareName;
    }

    @Override
    public void run() {
//        实现同步，解决shareName引起的线程安全
        Lock lock=new ReentrantLock();
        lock.lock();
            String name = Thread.currentThread().getName();
            if (name.equals("A1")){
                this.shareName="s2";
                System.out.println("A1 修改--- :" + name +" shareName :"+shareName);
            }else if (name.equals("A2")){
                this.shareName="s3";
                System.out.println("A2 修改--- :" + name +" shareName :"+shareName);
            }else {
                this.shareName="s4";
                System.out.println("A3 修改--- :" + name +" shareName :"+shareName);
            }
            System.out.println("current thread run name :" + name +" shareName :"+shareName);
            lock.unlock();
    }

    public static void main(String[] args){
        ThreadShare_solve1 threadShare=new ThreadShare_solve1("s1");
        Thread thread=new Thread(threadShare,"A1");
        Thread thread1=new Thread(threadShare,"A2");
        Thread thread2=new Thread(threadShare,"A3");
        thread.start();
        thread1.start();
        thread2.start();
    }
}
